#
#    Copyright 2006 Andrew Wilkinson <aw@cs.york.ac.uk>.
#
#    This file is part of PyScobble (http://lastfm.indiegigs.co.uk/pyscrobble)
#
#    PyScobble is free software; you can redistribute it and/or modify
#    it under the terms of the GNU Lesser General Public License as published by
#    the Free Software Foundation; either version 2.1 of the License, or
#    (at your option) any later version.
#
#    PyScobble is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public License
#    along with PyScobble; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

import httplib
import socket
import time
from xml.dom.minidom import parseString

query_delay = 2;

audioscrobbler_webservices = "ws.audioscrobbler.com"

last_query = None

def getDomText(nodelist):
    rc = ""
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc = rc + node.data
    return rc

def getDom(server, page, count = 0):
    global last_query
    if last_query is not None and last_query > time.time() - query_delay:
        time.sleep(last_query - (time.time() - query_delay))
    last_query = time.time()

    conn = httplib.HTTPConnection(server)
    setStatus("Downloading " + page.encode("utf8"))
    try:
        conn.request("GET", page.encode("utf8"))
    except socket.error, (code, msg): # Timeout error
        if code == 10060 and count < 5:
            setStatus("Timeout downloading " + page.encode("utf8"))
            time.sleep(30)
            return getDom(server, page, count + 1)
        raise

    try:
        s = parseString(conn.getresponse().read())
    except httplib.BadStatusLine:
        if count < 5: # timeout
            setStatus("Bad status line downloading " + page.encode("utf8"))
            time.sleep(30)
            return getDom(server, page, count + 1)
        raise
    else:
        webHit()
        return s

status = ""

def setStatus(text):
    global status
    status = text

def getStatus():
    return status

dbhit = 0
webhit = 0

def dbHit():
    global dbhit
    dbhit += 1
def webHit():
    global webhit
    webhit += 1

def getCacheUsage():
    try:
        return (dbhit*100.0)/(webhit+dbhit)
    except ZeroDivisionError:
        return 0.0

def resetStats():
    global dbhit, webhit, status
    dbhit = 0
    webhit = 0
    status = ""
